package com.epfresh.supplier.wxapi;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.WebPDFActivity;
import com.epfresh.supplier.entity.HomeNewEvenbus;
import com.epfresh.supplier.wxapi.pay.alipay.PayResult;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class WXPayEntryActivity extends BaseActivity implements PhotoCore.PhotoResult {
    private WebView webview;
    private ProgressBar progressBar;
    private String url;
    private String name;
    private IWXAPI api;
    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "avatar";
    private int apphandle = 0;//0是交给浏览器处理 1是把页面关闭
    private String gotoWebUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        initData();
    }

    @Override
    protected View getToolBar() {
        return null;
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, wxHandler);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
            return;
        }
        if (photoCore != null) photoCore.onResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void initData() {
        url = getIntent().getStringExtra("url");
        name = getIntent().getStringExtra("name");
        Log.e("url", url);
        initView();
        webViewSetting();
        loadWebView();
        initWeiXin();
    }

    private void initView() {
        progressBar = findViewById(R.id.pb);
        webview = findViewById(R.id.wv);
        choosePicInit();
    }

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        //  settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//https 页面里面有http形式的图片地址
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        webview.addJavascriptInterface(new JsToJava(), "android");
        //settings.setUserAgentString("User-Agent:Android");
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (progressBar.getVisibility() == View.GONE)
                        progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
//                if (title != null && !"".equals(title))
//                    toolbarTitle.setText(title);
            }
        });
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public void onLoadResource(WebView view, String url) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }

    private void loadWebView() {
        if (!TextUtils.isEmpty(url)) {
            webview.loadUrl(url);
        } else {
            toast("错误");
        }
    }

    private void choosePicInit() {
        filePath = filePath + "_" + "reg.jpg";
        photoCore = new PhotoCore(this, this);
        photoCore.setResultHeight(1500);
        photoCore.setResultWidth(1500);
    }

    private void takePhoto() {
        if (photoCore != null) {
            photoCore.setCrop(false);
            photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, false);
        }
    }

    @Override
    public void onBackPressed() {
        //  super.onBackPressed();
        if (!TextUtils.isEmpty(gotoWebUrl)) {
            webview.loadUrl(gotoWebUrl);
            gotoWebUrl = "";
        } else if (webview.canGoBack() && apphandle == 0) {
            webview.goBack();
        } else if (!webview.canGoBack() && name.equals("payMain")) {
            EventBus.getDefault().post(new HomeNewEvenbus());
            finish();
        } else {
            finish();
        }

    }

    @Override
    public void onSuccess(String path) {
        try {
            String file = FileUtil.encodeBase64File(filePath);
            webview.loadUrl("javascript:getFromAndroid(\"" + file + "\")");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onFail(String msg) {
        T.toast(msg);
    }

    @Override
    public void onReupload() {

    }

    public class JsToJava {
        @JavascriptInterface
        public void execute(final String message) {
        }

        @JavascriptInterface
        public void pageFinish() {
            if (name.equals("payMain")) {
                EventBus.getDefault().post(new HomeNewEvenbus());
            }
            finish();
        }

        @JavascriptInterface
        public void tokenInvalid() {
        }

        @JavascriptInterface
        public void weixinPay(String parm, String url) {
            payWeixin(parm, url);
        }

        @JavascriptInterface
        public void zhifubaoPay(String parm, String parm2) {
            Log.e("zhifu", "parm1:" + parm + "   parm2:" + parm2);
            aliPay(parm, parm2);
        }

        @JavascriptInterface
        public void showPDF(String pdfUrl, String titleName) {
            if (TextUtils.isEmpty(pdfUrl) || TextUtils.isEmpty(titleName)) {
                toast("pdf参数不能为空");
                return;
            }
            Intent intent = new Intent(WXPayEntryActivity.this, WebPDFActivity.class);
            intent.putExtra("pdfUrl", pdfUrl);
            intent.putExtra("titleName", titleName);
            startActivity(intent);
        }

        @JavascriptInterface
        public void photo() {
            takePhoto();
        }

        @JavascriptInterface
        public void isAppHandle(int isapphandle) {
            apphandle = isapphandle;
        }

        @JavascriptInterface
        public void toPageWeb(String url) {
            gotoWebUrl = url;
        }
    }

    private void initWeiXin() {
        api = WXAPIFactory.createWXAPI(this, "wx66a2b5cd16ea5da3");
        api.handleIntent(getIntent(), wxHandler);
    }

    String mUrl;

    private void payWeixin(final String parms, String url) {
        if (TextUtils.isEmpty(parms) || parms.split("&").length < 7) {
            T.toast("字符参数不对");
            return;
        }
        mUrl = url;
        Log.e("zhifu", "parm1:" + parms);
        PayReq request = new PayReq();
        request.appId = parms.split("&")[0];//wx66a2b5cd16ea5da3
        request.nonceStr = parms.split("&")[1];
        request.packageValue = "Sign=WXPay";
        request.partnerId = parms.split("&")[3];//1412367502
        request.prepayId = parms.split("&")[4];
        request.sign = parms.split("&")[5];
        request.timeStamp = parms.split("&")[6];

        api = WXAPIFactory.createWXAPI(WXPayEntryActivity.this, "wx66a2b5cd16ea5da3");
        api.registerApp("wx66a2b5cd16ea5da3");
        if (isWxInstall()) {
            api.sendReq(request);
        } else {
            T.toast("请先安装微信");
        }
    }

    public boolean isWxInstall() {
        return api != null && api.isWXAppInstalled();
    }

    IWXAPIEventHandler wxHandler = new IWXAPIEventHandler() {
        @Override
        public void onReq(BaseReq baseReq) {
            Log.e("wxHandler", "BaseReq:" + JsonUtils.toJson(baseReq));
        }

        @SuppressLint("LongLogTag")
        @Override
        public void onResp(BaseResp resp) {
            if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
                if (resp.errCode == 0) {
                    Toast.makeText(WXPayEntryActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    webview.loadUrl(mUrl + "&result=true");
                } else if (resp.errCode == -2) {
                    Toast.makeText(mContext, "取消支付", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(WXPayEntryActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    webview.loadUrl(mUrl + "&result=false");
                }
            }
        }
    };


    private void aliPay(final String aliPayParam, String url) {
        mUrl = url;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(WXPayEntryActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(aliPayParam, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    //9000	订单支付成功
                    //8000	正在处理中
                    //4000	订单支付失败
                    //6001	用户中途取消
                    //6002	网络连接出错
                    if (TextUtils.equals(resultStatus, "9000")) {
                        toast("支付成功");
                        webview.loadUrl(mUrl + "&result=true");
                    } else if ("8000".equals(resultStatus)) {
                        toast("正在处理中");
                    } else if ("4000".equals(resultStatus)) {
                        toast("订单支付失败");
                        webview.loadUrl(mUrl + "&result=false");
                    } else if ("6001".equals(resultStatus)) {
                        toast("取消支付");
                    } else if ("6002".equals(resultStatus)) {
                        toast("网络连接出错");
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };
}
